/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import * as Proto from '../protocol';
import { ITypeScriptServiceClient } from '../typescriptService';
import { tagsMarkdownPreview } from '../utils/previewer';
import * as typeConverters from '../utils/typeConverters';
import { 是需要翻译文本 } from './cts/ctsUtils/utils';
import { 翻译标识符 } from './cts/ctsTranslate/translateIdentifier';
import { 标识符_ } from './cts/ctsEnumsAndTypes/enumsAndTypes';

const 显示部件正则 = /^\((.*?)\)\s*(.*)/;

class TypeScriptHoverProvider implements vscode.HoverProvider {

	public constructor(
		private readonly client: ITypeScriptServiceClient
	) { }

	public async provideHover(
		document: vscode.TextDocument,
		position: vscode.Position,
		token: vscode.CancellationToken
	): Promise<vscode.Hover | undefined> {
		const filepath = this.client.toOpenedFilePath(document);
		if (!filepath) {
			return undefined;
		}

		const args = typeConverters.Position.toFileLocationRequestArgs(filepath, position);
		const response = await this.client.interruptGetErr(() => this.client.execute('quickinfo', args, token));
		const 范围 = document.getWordRangeAtPosition(position);
		let 当前文本 ="";
		let 翻译结果!:标识符_;
		if (范围) {
			当前文本 = document.getText(范围);
			if(是需要翻译文本(当前文本)){
				翻译结果 = await 翻译标识符({原文:当前文本})
			}
		}
		if (response.type !== 'response' || !response.body) {
			if (翻译结果) {
				return new vscode.Hover(`[翻译：](#) ${翻译结果.译文组![0].译文}`);
			}
			return undefined;
		}

		return new vscode.Hover(
			TypeScriptHoverProvider.getContents(response.body, 翻译结果 ? 翻译结果.译文组![0].译文 : ""),
			typeConverters.Range.fromTextSpan(response.body));
	}

	private static getContents(data: Proto.QuickInfoResponseBody, 当前单词?: string) {
		const parts = [];
		if (data.displayString) {
			data.displayString = data.displayString.replace(显示部件正则, (s1, s2, s3) => {
				if (s2) {
					parts.push(`[${s2}：](${s2})`);
				}
				return s3 || s1;
			});
			parts.push({ language: 'ctsscript', value: data.displayString });
		}

		const tags = tagsMarkdownPreview(data.tags);

		if (data.tags && data.tags.length) {
			const tag = data.tags[0];
			if (tag.name === "dict") {
				parts.push(`[词典： ${tag.text}](#)`);
			}
		}

		parts.push(data.documentation + (tags ? '\n\n' + tags : ''));
		if (当前单词) {
			parts.unshift(`[翻译：](#) ${当前单词}`);
		}
		return parts;
	}
}

export function register(
	selector: vscode.DocumentSelector,
	client: ITypeScriptServiceClient
): vscode.Disposable {
	return vscode.languages.registerHoverProvider(selector,
		new TypeScriptHoverProvider(client));
}